package com.inspur.security.cbb3.kms.keymanager.secrets.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.security.cbb3.kms.annotation.SysLog;
import com.inspur.security.cbb3.kms.enums.BusinessType;
import com.inspur.security.cbb3.kms.enums.SystemCode;
import com.inspur.security.cbb3.kms.keymanager.keyorders.vo.KeyOrdersAddVO;
import com.inspur.security.cbb3.kms.keymanager.secrets.po.SecretsBean;
import com.inspur.security.cbb3.kms.keymanager.secrets.service.SecretsService;
import com.inspur.security.cbb3.kms.keymanager.secrets.vo.AbstractSecretVO;
import com.inspur.security.cbb3.kms.keymanager.secrets.vo.SecretsAddVO;
import com.inspur.security.cbb3.kms.utils.PageRequestDate;
import com.inspur.security.cbb3.kms.utils.ResultUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 密钥控制类
 *
 * @author lijunchang
 */
@RestController
@RequestMapping("/v1/secrets")
@ApiModel(value = "密钥业务", description = "密钥业务")
@Slf4j
public class SecretsController {

    @Autowired
    private SecretsService secretsService;

    @PostMapping
    @ApiOperation(value = "密钥上传", notes = "密钥上传", httpMethod = "POST")
    @SysLog(title = "密钥上传", businessType = BusinessType.INSERT, isSaveRequestData = true)
    public ResponseEntity uploadSecrets(@ApiParam(value = "传入新增密钥对象", required = true) @Valid SecretsAddVO secretsAddVO) {
        SecretsBean bean = secretsService.uploadSecrets(secretsAddVO);
        Map<String, String> returnMap = new HashMap<>(1);
        returnMap.put("secretRef", "/v1/secrets/" + bean.getUuid());
        return ResultUtil.objReturn(returnMap, HttpStatus.CREATED);
    }

    @GetMapping
    @ApiOperation(value = "密钥列表查询", notes = "密钥列表查询", httpMethod = "GET")
    public ResponseEntity searchSecrets(@ApiParam(value = "传入分页条件") PageRequestDate pageRequestDate,
                                        @ApiParam(value = "传入查询条件") SecretsBean searchParams) {
        Page page = secretsService.searchSecrets(pageRequestDate, searchParams);
        Map<String, Object> returnMap = new HashMap<>(2);
        returnMap.put("total", page.getTotalElements());
        if (page.getTotalElements() < 1) {
            returnMap.put("secrets", null);
            return ResultUtil.objReturn(returnMap, HttpStatus.OK);
        }
        List<SecretsBean> list = page.getContent();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        for (SecretsBean bean : list) {
            bean.setDownloadRef("/v1/secrets/" + bean.getUuid() + "/payload");
        }
        returnMap.put("secrets", list);
        return ResultUtil.objReturn(returnMap, HttpStatus.OK);
    }

    @GetMapping("/{uuid}")
    @ApiOperation(value = "密钥单个信息查询", notes = "密钥单个信息查询,请将{uuid}替换成密钥主键", httpMethod = "GET")
    public ResponseEntity searchSecret(@PathVariable("uuid") String uuid) throws MissingServletRequestParameterException, NotFoundException {
        SecretsBean bean = secretsService.searchSecret(uuid);
        bean.setDownloadRef("/v1/secrets/" + bean.getUuid() + "/payload");
        return ResultUtil.objReturn(bean, HttpStatus.OK);
    }

//    @PutMapping("/{uuid}")
//    @ApiOperation(value = "更换密钥", notes = "更换密钥,请将{uuid}替换成密钥主键", httpMethod = "PUT")
//    public ResponseEntity changeOrder(@PathVariable("uuid") String uuid) throws MissingServletRequestParameterException, NotFoundException {
////        SecretsBean bean = secretsService.changeOrder(uuid);
////        assembleKeyOrdersBean(bean);
////        return ResultUtil.objReturn(bean, HttpStatus.NO_CONTENT);
//        return null;
//    }


    @DeleteMapping("/{uuid}")
    @ApiOperation(value = "删除密钥", notes = "可以删除一条密钥信息", httpMethod = "DELETE")
    @SysLog(title = "删除密钥", businessType = BusinessType.DELETE)
    public ResponseEntity deleteSecret(@PathVariable("uuid") String uuid) throws MissingServletRequestParameterException, NotFoundException {
        secretsService.deleteSecret(uuid);
        return ResultUtil.noDataReturn(SystemCode.SUCCESS, HttpStatus.NO_CONTENT);
    }

    @GetMapping("/{uuid}/payload")
    @ApiOperation(value = "下载密钥", notes = "下载密钥,请将{uuid}替换成密钥主键", httpMethod = "GET")
    @SysLog(title = "下载密钥", businessType = BusinessType.EXPORT)
    public ResponseEntity downloadSecret(@PathVariable("uuid") String uuid) throws MissingServletRequestParameterException, NotFoundException {
        String secretContent = secretsService.downloadSecret(uuid);
        return ResultUtil.objReturn(secretContent, HttpStatus.OK);
    }


}
